<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>侦听器</title>
    <script src="./vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
</head>
<body>
    <div id="watch-example">
        <p>
            ask a yes/no question:
            <input v-model="question">
        </p>
        <p>{{ answer }}</p>
    </div>
    <script>
        var watchExampleVM = new Vue({
            el: "#watch-example",
            data: {
                question: "",
                answer: "I cannot give your a answer until you ask a question!"
            },
            // watch:适用于当需要数据变化执行异步/开销较大的操作
            // computed没有无法做到这两点
            watch: {
                // 如果question发生变化，这个函数执行
                question: function (newQuestion, oldQuestion) {
                    this.answer = "waiting for you to stop typing...";
                    this.debouncedGetAnswer();
                }
            },
            created: function () {
                this.debouncedGetAnswer =  _.debounce(this.getAnswer, 500);
            },
            methods: {
                getAnswer: function () {
                    if (this.question.indexOf("?") === -1) {
                        this.answer =  "question usually contains a question mark.";
                        return;
                    }
                    this.answer = "thinking...";
                    var vm = this;
                    axios.get("https://yesno.wtf/api")
                        .then(function (response) {
                            vm.answer = _.capitalize(response.data.answer);
                        })
                        .catch(function (error) {
                            vm.answer = "Error!Could not reach the api." + error;
                        })
                }
            }
        });
    </script>
</body>
</html>